import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UtilsService } from './utils.service';
import { NzNotificationService } from 'ng-zorro-antd';
import { baseApi } from 'src/app/data/urls';

@Injectable({
  providedIn: 'root'
})
export class RequestService {


  public baseUrl: string = baseApi;
  constructor(private http: HttpClient, private util: UtilsService, private notification: NzNotificationService) {

  }

  /**
   * 请求接口左侧补齐'/'
   *
   */
  private static trimLeft(str: string) {
    if (str.substr(0, 1) !== '/') {
      str = '/' + str;
    }
    return str;
  }


  async get({ url = '', headers = null, errorMsg = '', successMsg = '', loading = true, successDuration = 1500, errorDuration = 3000 }) {
    return await this.common(url, headers, null, errorMsg, successMsg, loading, 'get', successDuration, errorDuration);
  }

  // tslint:disable-next-line:max-line-length
  async post({ url = '', headers = null, data = null, errorMsg = '', successMsg = '', loading = true, successDuration = 1000, errorDuration = 2000 }) {
    return await this.common(url, headers, data, errorMsg, successMsg, loading, 'post', successDuration, errorDuration);
  }
  // tslint:disable-next-line:max-line-length
  async common(url: string, headers: any, data: any, errorMsg: string, successMsg: string, loading: boolean, method: string, successDuration: number, errorDuration: number) {

    // 0.3秒之内的则不显示loading, 无论是否要显示loading,避免一闪而过的情况
    let showLoading = false;
    const time = setTimeout(() => {
      if (loading) {
        showLoading = true;
        this.util.loading.next(true);
      }
    }, 300);
    if (headers != null) {

      const httpOptions = {
        headers: new HttpHeaders()
      };
      const keys = Object.keys(headers);
      keys.forEach(item => {
        httpOptions.headers = httpOptions.headers.set(item, headers[item]);
      });
      let res: any;
      try {
        if (method === 'post') { res = await this.http.post((this.baseUrl + RequestService.trimLeft(url)), data, httpOptions).toPromise(); }
        if (method === 'get') { res = await this.http.get((this.baseUrl + RequestService.trimLeft(url)), httpOptions).toPromise(); }
        clearTimeout(time);
        return this.check(res, successMsg, errorMsg, loading, showLoading, successDuration, errorDuration);
      } catch (error) {
        // 遇到错误时判断是否加载,错误必然过不clearTimeout此句上方 故无需判断
        clearTimeout(time);
        if (loading) {
          this.util.loading.next(false);
        }
      }

    } else {
      try {
        let res: any;
        if (method === 'post') { res = await this.http.post((this.baseUrl + RequestService.trimLeft(url)), data).toPromise(); }
        if (method === 'get') { res = await this.http.get(this.baseUrl + RequestService.trimLeft(url)).toPromise(); }
        clearTimeout(time);
        return this.check(res, successMsg, errorMsg, loading, showLoading, successDuration, errorDuration);
      } catch (error) {
        clearTimeout(time);
        this.notification.error('失败', '服务器错误!');
        if (loading) {
          this.util.loading.next(false);
        }
      }

    }

  }
  // tslint:disable-next-line:max-line-length
  private check(res: any, successMsg: string, errorMsg: string, loading: boolean, showLoading: boolean, successDuration: number, errorDuration: number) {

    if (loading && showLoading) {
      this.util.loading.next(false);
    }
    if (res.code === 200) {
      if (successMsg != null) {
        if (successMsg === '') {
          // 显示返回的msg
          this.notification.success('成功', res.msg, { nzDuration: successDuration ? successDuration : 1000 });
        } else {
          // 显示自定义的msg
          this.notification.success('成功', successMsg, { nzDuration: successDuration ? successDuration : 1000 });
        }
      }
      return res.data ? res.data : true;
    }

    if (res.code === 500) {
      if (errorMsg != null) {
        if (errorMsg === '') {
          // 显示返回的msg
          this.notification.error('失败', res.msg, { nzDuration: successDuration ? errorDuration : 1000 });
        } else {
          // 显示自定义的msg
          this.notification.error('失败', errorMsg, { nzDuration: successDuration ? errorDuration : 1000 });
        }
      }
      return null;
    }

    if (res.code === 401) {
      if (errorMsg != null) {
        if (errorMsg === '') {
          // 显示返回的msg
          this.notification.error('失败', res.msg, { nzDuration: successDuration ? errorDuration : 1000 });
        } else {
          // 显示自定义的msg
          this.notification.error('失败', errorMsg, { nzDuration: successDuration ? errorDuration : 1000 });
        }
      }
      return null;
    }


  }
}
